package com.kaluli.project.service;

import java.util.HashMap;


public class TradePool {
	private volatile boolean inited = false;

	private static TradePool tradePool = null;

	private HashMap<String, TradeThread> tradeThreadMap = null;

	private HashMap<String, TradeContext> contextMap = null;

	private HashMap<String, TradeQueue> tradeQueueMap = null;

	private HashMap<String, Thread> threadMap = null;

	private TradePool() {
		tradeThreadMap = new HashMap<String, TradeThread>();
		contextMap = new HashMap<String, TradeContext>();
		tradeQueueMap = new HashMap<String, TradeQueue>();
		threadMap = new HashMap<String, Thread>();
		// preTradeList=new LinkedList<Trade>();
		// preTradeQueueMap=new HashMap<String,TradeQueue>();
	}

	public static synchronized TradePool getTradeInstance() {
		if (tradePool == null) {
			tradePool = new TradePool();
		}
		return tradePool;
	}

	public TradeThread getTradeThread(String msgChannel) {

		TradeThread thread = null;
		if (tradeThreadMap.get(msgChannel) != null) {
			thread = tradeThreadMap.get(msgChannel);
		} else {
			TradeContext context = getTradeContext(msgChannel);
			TradeQueue queue = getTradeQueue(msgChannel);
			thread = new TradeThread(msgChannel, context, queue);
			tradeThreadMap.put(msgChannel, thread);
		}
		return thread;
	}

	public TradeContext getTradeContext(String msgChannel) {

		TradeContext context = null;
		if (contextMap.get(msgChannel) != null) {
			context = contextMap.get(msgChannel);
		} else {
			context = new TradeContext(msgChannel);
			contextMap.put(msgChannel, context);
		}
		return context;
	}

	/**
	 * 根据渠道类型获取主卖主卖队列
	 * 
	 * @param msgChannel
	 * @return
	 */
	public TradeQueue getTradeQueue(String msgChannel) {

		TradeQueue queue = null;
		if (tradeQueueMap.get(msgChannel) != null) {
			queue = tradeQueueMap.get(msgChannel);
		} else {
			queue = new TradeQueue(msgChannel);
			tradeQueueMap.put(msgChannel, queue);
		}
		return queue;
	}

	/**
	 * 启动某渠道线程
	 * 
	 * @param msgChannel
	 */
	public void startTradeThread(String msgChannel) {
		TradeThread tradeThread = getTradeThread(msgChannel);
		if (tradeThread != null) {
			// tradeThread= tradeThreadMap.get(currencyType);

			Thread thread = new Thread(tradeThread);
			thread.setName("tradeThread-" + msgChannel);
			thread.start();
			threadMap.put(msgChannel, thread);
		}
	}
	
	/**
     * 初始化某渠道的线程
     * @param msgChannel
     */
    public void initTradeThread(String msgChannel){
    	TradeThread tradeThread =  getTradeThread(msgChannel);
		if(tradeThread!=null){
			tradeThread= tradeThreadMap.get(msgChannel);
			Thread thread = new Thread(tradeThread);
		    thread.setName("tradeThread-"+msgChannel);
		    thread.start();
		    threadMap.put(msgChannel, thread);
		}
		
    }
}
